import React from 'react';
import { View, ScrollView, Alert, Pressable } from 'react-native';
import { useTranslation } from 'react-i18next';
import { useMMKVBoolean, useMMKVObject } from '@/hooks/useMMkv';
import eventBus from '@/utils/eventBus';
import Settings from '@/assets/icon/settings.svg';
import Account from '@/assets/icon/account.svg';
import Skin from '@/assets/icon/skin.svg';
import Global from '@/assets/icon/global.svg';
import Network from '@/assets/icon/network.svg';
import {
  Text,
  Button,
  Icon,
  useAppTheme,
  Cell,
  type CellDataType,
  Switch,
  Card,
} from 'tsun-smart-ui';
import Avatar from '@/components/Avatar';
import { UserInfo } from '@/services/api/userApi';
import { useDispatch } from 'react-redux';
import { resetAllState } from '@/store/actions/resetActions';
import DebuggingEntranceButton from '../Debugging/DebuggingEntranceButton';

const ProfilePage = ({
  navigation,
}: ReactNavigation.RootStackScreenProps<'UserProfile'>) => {
  const { t } = useTranslation();
  const theme = useAppTheme();
  const dispatch = useDispatch();
  const [userInfo] = useMMKVObject<UserInfo>('user_info');
  console.log('userInfo1111111', userInfo);
  const [globalMode = true, setGlobalMode] = useMMKVBoolean('globalMode');
  // 获取用户角色显示文本
  const getUserRoleText = (userType?: number) => {
    switch (userType) {
      case 2:
        return t('settings.supplier.installer', {
          defaultValue: '安装商/运营商',
        });
      case 1:
      default:
        return t('personal.Owner', { defaultValue: '业主' });
    }
  };

  // 处理用户退出登录
  const handleLogout = () => {
    Alert.alert(t('messageBox.logout'), t('user.logOutMessage'), [
      {
        text: t('user.logOutCancel'),
        style: 'cancel',
      },
      {
        text: t('common.confirmButtonText'),
        onPress: () => {
          eventBus.emit('LOGOUT_REQUIRED');
          dispatch(resetAllState());
        },
      },
    ]);
  };

  // 切换全场景模式
  const toggleGlobalMode = () => {
    setGlobalMode(!globalMode);
  };

  // 导航到通用设置
  const goToGeneralSettings = () => {
    navigation.navigate('General');
  };

  // 导航到账号安全
  const goToAccountSecurity = () => {
    navigation.navigate('AccountSecurity');
  };

  // 导航到皮肤设置
  const goToThemeSettings = () => {
    navigation.navigate('ThemeSettings');
  };

  const Actions: CellDataType[] = [
    {
      left: (size: number) => (
        <Settings
          color={theme.colors?.neutral?.title}
          width={size}
          height={size}
        ></Settings>
      ),
      title: t('common.general'),
      onPress: goToGeneralSettings,
    },
    {
      left: (size: number) => (
        <Account
          color={theme.colors?.neutral?.title}
          width={size}
          height={size}
        ></Account>
      ),
      title: t('userSetting.account_security'),
      onPress: goToAccountSecurity,
    },
    {
      left: (size: number) => (
        <Skin
          color={theme.colors?.neutral?.title}
          width={size}
          height={size}
        ></Skin>
      ),
      title: t('layout.skin'),
      onPress: goToThemeSettings,
    },
  ];
  return (
    <>
      <ScrollView className="mx-4 mt-2">
        {/* 顶部用户信息 */}
        <Card>
          <Pressable
            onPress={() => {
              navigation.navigate('UserProfile');
            }}
            className="flex-row flex-between"
          >
            <Avatar
              needUpload={false}
              uri={userInfo?.avatar}
              className=" size-[60px]"
            />
            <View className="items-start ml-[15] mr-auto">
              <Text variant="navTitle">{userInfo?.nickname}</Text>
              <Text
                variant="caption"
                style={{
                  color: theme.colors?.neutral?.primary,
                }}
              >
                {getUserRoleText(userInfo?.userType)}
              </Text>
              {userInfo?.userType === 2 ? (
                <View className="flex-row items-center mt-2">
                  <Text
                    style={{
                      color: theme.colors?.neutral?.primary,
                      fontWeight: 500,
                    }}
                  >
                    {userInfo.instName}
                  </Text>
                </View>
              ) : (
                <Text
                  style={{
                    color: theme.colors?.neutral?.primary,
                  }}
                >
                  {userInfo?.email || 'neo@tsun.com'}
                </Text>
              )}
            </View>
            <Icon
              name="right"
              size={10}
              color={theme.colors?.neutral?.primary}
            ></Icon>
          </Pressable>
        </Card>
        {/* 设置列表 */}
        <View className="  my-3 rounded-lg">
          <Cell
            listItemStyle={{
              paddingTop: 21,
              paddingBottom: 21,
            }}
            data={Actions}
          ></Cell>
        </View>
        {userInfo?.userType === 1 && (
          <Cell
            className=" mb-3"
            listItemStyle={{
              paddingTop: 18,
              paddingBottom: 18,
            }}
            data={[
              {
                title: t('common.networkTool', {
                  defaultValue: '配网工具',
                }),
                left: (size) => (
                  <Network
                    color={theme.colors?.neutral?.title}
                    width={size}
                    height={size}
                  ></Network>
                ),
                onPress: () => {
                  navigation.navigate('Scan', {
                    setupNetworkOnly: true,
                  });
                },
              },
            ]}
          ></Cell>
        )}
        {/* 全球景模式开关 */}
        <Cell
          className=" mb-3"
          listItemStyle={{
            paddingTop: 18,
            paddingBottom: 18,
          }}
          data={[
            {
              title: t('settings.full.scene.mode'),
              left: (size) => (
                <Global
                  color={theme.colors?.neutral?.title}
                  width={size}
                  height={size}
                ></Global>
              ),
              right: (
                <Switch value={globalMode!} onValueChange={toggleGlobalMode} />
              ),
            },
          ]}
        ></Cell>

        {/* 退出登录按钮 */}
        <Button
          onPress={handleLogout}
          title={t('user.dropdown5')}
          style={{
            backgroundColor: theme.colors?.neutral?.white,
            borderRadius: 8,
          }}
          textStyle={{
            color: theme.colors?.neutral?.tip,
          }}
        />

        <DebuggingEntranceButton
          style={{
            alignSelf: 'center',
            height: 100,
            width: 240,
            marginTop: 24,
          }}
        />
      </ScrollView>
    </>
  );
};

export default ProfilePage;
